<template>
  <div class="geometry-container">
    <!-- 左侧表单 -->
    <div class="geometry-form">
      <el-form :model="geometryForm" label-width="40px">
        <el-form-item label="type">
          <el-select v-model="geometryForm.type">
            <el-option label="Polygon" value="Polygon" />
            <el-option label="Polyline" value="Polyline" />
            <el-option label="PointSet" value="PointSet" />
          </el-select>
        </el-form-item>
        <el-form-item label="name">
          <el-input v-model="geometryForm.name" placeholder="please input shape name" />
        </el-form-item>

        <!-- 坐标列表 -->
        <el-form-item label="index">
          <div v-for="(point, index) in geometryForm.coordinates" :key="index" 
               class="coordinate-item" 
               :class="{ 'editing': editingPointIndex === index }"
               @click="setEditingPoint(index)">
            <div class="coordinate-header">
              <span class="point-index">point{{ index + 1 }}</span>
              <el-button type="danger" link @click.stop="removePoint(index)">
                <el-icon><Delete /></el-icon>
              </el-button>
            </div>
            <div class="coordinate-content">
              <div class="input-group">
                <span class="input-label">X:</span>
                <el-input-number
                  v-model="point.x"
                  :min="0"
                  :max="1"
                  :step="0.1"
                  :precision="2"
                  controls-position="right"
                  class="full-width"
                />
              </div>
              <div class="input-group">
                <span class="input-label">Y:</span>
                <el-input-number
                  v-model="point.y"
                  :min="0"
                  :max="1"
                  :step="0.1"
                  :precision="2"
                  controls-position="right"
                  class="full-width"
                />
              </div>
              <!-- 当类型为点集合时显示角度参数 -->
              <template v-if="geometryForm.type === 'PointSet'">
                <div class="input-group">
                  <span class="input-label">yaw:</span>
                  <el-input-number
                    v-model="point.yaw"
                    :min="0"
                    :max="1"
                    :step="0.1"
                    :precision="2"
                    controls-position="right"
                    class="full-width"
                  />
                </div>
                <div class="input-group">
                  <span class="input-label">pitch:</span>
                  <el-input-number
                    v-model="point.pitch"
                    :min="0"
                    :max="1"
                    :step="0.1"
                    :precision="2"
                    controls-position="right"
                    class="full-width"
                  />
                </div>
                <div class="input-group">
                  <span class="input-label">roll:</span>
                  <el-input-number
                    v-model="point.roll"
                    :min="0"
                    :max="1"
                    :step="0.1"
                    :precision="2"
                    controls-position="right"
                    class="full-width"
                  />
                </div>
              </template>
            </div>
          </div>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" link @click="addPoint">
            <el-icon><Plus /></el-icon>
            add point
          </el-button>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleAdd" :disabled="!canAdd">add shape</el-button>
        </el-form-item>
      </el-form>

      <!-- 已有图形列表 -->
      <div class="geometry-list">
        <el-divider content-position="left">shape list</el-divider>
        <el-table :data="geometryList" style="width: 100%">
          <el-table-column prop="name" label="name" />
          <el-table-column prop="type" label="type" />
          <el-table-column label="operate" width="120">
            <template #default="scope">
              <el-button type="primary" link @click="handleRename(scope.row)">
                rename
              </el-button>
              <el-button type="danger" link @click="handleDelete(scope.row)">
                delete
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <!-- 右侧画布 -->
    <div class="geometry-canvas" :style="backgroundStyle" ref="canvasContainer">
      <canvas ref="canvas"></canvas>
    </div>
  </div>
</template>

<script setup>
import {ref, reactive, computed, onMounted, watch, onBeforeUnmount} from 'vue'
import { deleteGeometry, getGeometryList, getMap, renameGeometry, addGeometry } from '../api'
import { ElMessage } from 'element-plus'
import { Delete, Plus } from '@element-plus/icons-vue'

const canvas = ref(null)
const canvasContainer = ref(null)
const ctx = ref(null)
const backgroundStyle = ref({})
const geometryList = ref([])
const editingPointIndex = ref(-1) // 当前正在编辑的坐标点索引

// 表单数据
const geometryForm = reactive({
  type: 'Polygon',
  name: '',
  coordinates: []
})

// 判断是否可以添加图形
const canAdd = computed(() => {
  if (!geometryForm.name) {
    return false
  }
  // 根据类型验证点的数量
  if (geometryForm.type === 'Polygon' && geometryForm.coordinates.length < 3) {
    return false
  }

  if (geometryForm.type === 'PointSet' && geometryForm.coordinates.length < 1) {
    return false
  }

  if (geometryForm.type === 'Polyline' && geometryForm.coordinates.length < 2) {
    return false
  }
  return true
})

// 添加坐标点
function addPoint() {
  const point = {
    x: 0,
    y: 0
  }

  // 如果是点集合类型，添加角度参数
  if (geometryForm.type === 'PointSet') {
    point.yaw = 0
    point.pitch = 0
    point.roll = 0
  }

  geometryForm.coordinates.push(point)
}

// 移除坐标点
function removePoint(index) {
  geometryForm.coordinates.splice(index, 1)
  // 如果删除的是当前编辑的点，重置编辑状态
  if (editingPointIndex.value === index) {
    editingPointIndex.value = -1
  } else if (editingPointIndex.value > index) {
    editingPointIndex.value--
  }
}

// 设置当前编辑的坐标点
function setEditingPoint(index) {
  editingPointIndex.value = index
  drawCurrentFormCoordinates() // 重新绘制以高亮当前编辑的点
}

// 新增图形
function handleAdd() {
  if (!geometryForm.name) {
    ElMessage.warning('please input shape name')
    return
  }

  addGeometry(geometryForm).then(res => {
    if (res.success) {
      ElMessage.success('add success')
      // 重置表单
      geometryForm.name = ''
      geometryForm.coordinates = []
      editingPointIndex.value = -1 // 重置编辑状态
      // 刷新列表
      fetchGeometryList()
    } else {
      ElMessage.error(res.message || 'add fail')
    }
  })
}

// 初始化画布
function initCanvas() {
  const container = canvasContainer.value
  const canvasEl = canvas.value
  canvasEl.width = container.clientWidth
  canvasEl.height = container.clientHeight
  ctx.value = canvasEl.getContext('2d')
}

// 绘制几何图形
function drawGeometry(geometry) {
  const { type, coordinates } = geometry
  const canvas = canvasContainer.value
  const scale = {
    x: canvas.clientWidth,
    y: canvas.clientHeight
  }

  ctx.value.beginPath()

  // 转换坐标
  const points = coordinates.map(point => ({
    x: point.x * scale.x,
    y: point.y * scale.y
  }))

  switch (type) {
    case 'Polygon':
      drawPolygon(points)
      break
    case 'Polyline':
      drawPolyline(points)
      break
    case 'PointSet':
      drawPointSet(points)
      break
  }
}

// 绘制多边形
function drawPolygon(points) {
  ctx.value.beginPath()
  ctx.value.moveTo(points[0].x, points[0].y)
  points.slice(1).forEach(point => {
    ctx.value.lineTo(point.x, point.y)
  })
  ctx.value.closePath()
  ctx.value.strokeStyle = '#409EFF'
  ctx.value.stroke()
  ctx.value.fillStyle = 'rgba(64, 158, 255, 0.2)'
  ctx.value.fill()
}

// 绘制多线段
function drawPolyline(points) {
  ctx.value.beginPath()
  ctx.value.moveTo(points[0].x, points[0].y)
  points.slice(1).forEach(point => {
    ctx.value.lineTo(point.x, point.y)
  })
  ctx.value.strokeStyle = '#67C23A'
  ctx.value.stroke()
}

// 绘制点集合
function drawPointSet(points) {
  points.forEach(point => {
    ctx.value.beginPath()
    ctx.value.arc(point.x, point.y, 4, 0, Math.PI * 2)
    ctx.value.fillStyle = '#F56C6C'
    ctx.value.fill()
  })
}

// 绘制当前表单中的坐标点（用于实时预览）
function drawCurrentFormCoordinates() {
  if (!ctx.value || geometryForm.coordinates.length === 0) return

  const canvas = canvasContainer.value
  const scale = {
    x: canvas.clientWidth,
    y: canvas.clientHeight
  }

  // 转换坐标
  const points = geometryForm.coordinates.map((point, index) => ({
    x: point.x * scale.x,
    y: point.y * scale.y,
    isEditing: editingPointIndex.value === index
  }))

  // 绘制形状预览（半透明）
  if (points.length >= 2) {
    ctx.value.save()
    ctx.value.globalAlpha = 0.5
    
    switch (geometryForm.type) {
      case 'Polygon':
        if (points.length >= 3) {
          ctx.value.beginPath()
          ctx.value.moveTo(points[0].x, points[0].y)
          points.slice(1).forEach(point => {
            ctx.value.lineTo(point.x, point.y)
          })
          ctx.value.closePath()
          ctx.value.strokeStyle = '#909399'
          ctx.value.stroke()
          ctx.value.fillStyle = 'rgba(144, 147, 153, 0.1)'
          ctx.value.fill()
        }
        break
      case 'Polyline':
        ctx.value.beginPath()
        ctx.value.moveTo(points[0].x, points[0].y)
        points.slice(1).forEach(point => {
          ctx.value.lineTo(point.x, point.y)
        })
        ctx.value.strokeStyle = '#909399'
        ctx.value.stroke()
        break
    }
    
    ctx.value.restore()
  }

  // 绘制所有坐标点
  points.forEach((point, index) => {
    ctx.value.beginPath()
    ctx.value.arc(point.x, point.y, point.isEditing ? 8 : 7, 0, Math.PI * 2)
    
    if (point.isEditing) {
      // 正在编辑的点用蓝色高亮
      ctx.value.fillStyle = '#409EFF'
      ctx.value.fill()
    } else {
      // 普通点用灰色
      ctx.value.fillStyle = '#909399'
      ctx.value.fill()
    }
    
    // 所有点都添加白色外圈
    ctx.value.strokeStyle = '#ffffff'
    ctx.value.lineWidth = 2
    ctx.value.stroke()
    
    // 绘制点的序号
    ctx.value.fillStyle = '#ffffff'
    ctx.value.font = '12px Arial'
    ctx.value.textAlign = 'center'
    ctx.value.textBaseline = 'middle'
    ctx.value.fillText(index + 1, point.x, point.y)
  })
}

// 获取背景图片
function getBackgroundImage() {
  getMap().then(res => {
    if (res.success) {
      backgroundStyle.value = {
        backgroundImage: `url(${res.image})`,
        backgroundSize: 'cover',
        backgroundPosition: 'center',
        backgroundRepeat: 'no-repeat'
      }
    }
  })
}

// 获取几何图形列表
function fetchGeometryList() {
  getGeometryList().then(res => {
    if (res.success) {
      geometryList.value = res.data
      // 清除画布并重新绘制所有图形
      ctx.value.clearRect(0, 0, canvas.value.width, canvas.value.height)
      geometryList.value.forEach(geometry => {
        drawGeometry(geometry)
      })
      // 绘制当前表单中的坐标点
      drawCurrentFormCoordinates()
    }
  })
}

// 重命名
function handleRename(row) {
  renameGeometry({
    id: row.id,
    newName: prompt('input new name', row.name)
  }).then(res => {
    if (res.success) {
      ElMessage.success('rename success')
      fetchGeometryList()
    } else {
      ElMessage.error(res.message || 'rename success')
    }
  })
}

// 删除图形
function handleDelete(row) {
  deleteGeometry({
    id: row.id
  }).then(res => {
    if (res.success) {
      ElMessage.success('delete success')
      fetchGeometryList()
    } else {
      ElMessage.error(res.message || 'delete fail')
    }
  })
}

// 监听类型变化，处理坐标点的参数
watch(() => geometryForm.type, (newType) => {
  if (newType === 'PointSet') {
    // 为现有的坐标点添加角度参数
    geometryForm.coordinates.forEach(point => {
      if (!point.hasOwnProperty('yaw')) {
        point.yaw = 0
        point.pitch = 0
        point.roll = 0
      }
    })
  } else {
    // 如果切换到其他类型，移除角度参数
    geometryForm.coordinates.forEach(point => {
      delete point.yaw
      delete point.pitch
      delete point.roll
    })
  }
  // 重新绘制
  if (ctx.value) {
    ctx.value.clearRect(0, 0, canvas.value.width, canvas.value.height)
    geometryList.value.forEach(geometry => {
      drawGeometry(geometry)
    })
    drawCurrentFormCoordinates()
  }
})

// 监听坐标变化，实时更新画布显示
watch(() => geometryForm.coordinates, () => {
  if (ctx.value) {
    ctx.value.clearRect(0, 0, canvas.value.width, canvas.value.height)
    geometryList.value.forEach(geometry => {
      drawGeometry(geometry)
    })
    drawCurrentFormCoordinates()
  }
}, { deep: true })

onMounted(() => {
  resizePreview()
  getBackgroundImage()
  initCanvas()
  fetchGeometryList()

  // 监听窗口大小变化，重新调整画布大小
  window.addEventListener('resize', () => {
    resizePreview()
    initCanvas()
    // 重新绘制所有内容
    if (ctx.value) {
      geometryList.value.forEach(geometry => {
        drawGeometry(geometry)
      })
      drawCurrentFormCoordinates()
    }
  })
})

function resizePreview() {
  if (canvasContainer.value) {
    canvasContainer.value.style.width = canvasContainer.value.offsetHeight + 'px'
  }
}

onBeforeUnmount(() => {
  window.removeEventListener('resize', resizePreview)
})
</script>

<style scoped>
.geometry-container {
  display: flex;
  height: 100%;
  gap: 20px;
  overflow: hidden;
}

.geometry-form {
  width: 600px;
  padding: 20px;
  background: #fff;
  border-radius: 4px;
  overflow-y: auto;
  overflow-x: hidden;
}

.geometry-canvas {
  height: 100%;
  width: 100%;
  background-color: #fff;
  border-radius: 4px;
  position: relative;
}

canvas {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}

.geometry-list {
  margin-top: 20px;
}

:deep(.el-divider__text) {
  font-size: 16px;
  font-weight: bold;
  color: #409EFF;
}

.coordinate-item {
  border: 1px solid #EBEEF5;
  border-radius: 4px;
  margin-bottom: 12px;
  padding: 12px;
  width: 100%;
  cursor: pointer;
  transition: all 0.3s ease;
}

.coordinate-item:hover {
  border-color: #C6E2FF;
  background-color: #F5F9FF;
}

.coordinate-item.editing {
  border-color: #409EFF;
  background-color: #F0F8FF;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}

.coordinate-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
  padding-bottom: 8px;
  border-bottom: 1px dashed #EBEEF5;
}

.point-index {
  font-size: 14px;
  font-weight: bold;
  color: #606266;
}

.coordinate-content {
  display: flex;
  flex-direction: column;
  gap: 12px;
  width: 100%;
}

.input-group {
  display: flex;
  align-items: center;
  width: 100%;
}

.input-label {
  width: 50px;
  color: #606266;
  font-size: 14px;
  text-align: right;
  margin-right: 8px;
  flex-shrink: 0;
}

:deep(.el-input-number) {
  flex: 1;
  width: auto;
}

:deep(.el-input-number .el-input__wrapper) {
  padding-right: 0;
}
</style>
